package it.francescogabbrielli.android.solidalapp.file;

import java.util.List;

import it.francescogabbrielli.android.solidalapp.ChatMessage;
import it.francescogabbrielli.android.solidalapp.R;
import android.content.Context;
import android.content.res.Resources;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ChatAdapter extends ArrayAdapter<ChatMessage> {

	public ChatAdapter(Context context, List<ChatMessage> list) {
		super(context, R.layout.message, R.id.text, list);
	}
	
	public int getPositionById(long id) {
		for (int i=0;i<getCount();i++)
			if (getItem(i).id == id)
				return i;
		return -1;
	}
	
	@Override
	@SuppressWarnings("deprecation")
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = super.getView(position, convertView, parent);
		TextView tv = (TextView) view.findViewById(R.id.text);
		ChatMessage m = getItem(position);
		LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tv.getLayoutParams();
		Resources res = getContext().getResources();
		switch (m.type) {
		case INCOMING:
			params.gravity = Gravity.RIGHT;
			tv.setBackgroundDrawable(res.getDrawable(R.drawable.snippet_right));
			tv.setTextColor(res.getColor(R.color.chat_message_sent));
			break;
		case ERROR:
			params.gravity = Gravity.LEFT;
			tv.setBackgroundDrawable(res.getDrawable(R.drawable.snippet_left));
			tv.setTextColor(res.getColor(R.color.chat_message_error));
			break;
		case SENDING:
			params.gravity = Gravity.LEFT;
			tv.setBackgroundDrawable(res.getDrawable(R.drawable.snippet_left));
			tv.setTextColor(res.getColor(R.color.chat_message_sending));
			break;
		case SENT:
			params.gravity = Gravity.LEFT;
			tv.setBackgroundDrawable(res.getDrawable(R.drawable.snippet_left));
			tv.setTextColor(res.getColor(R.color.chat_message_sent));
			break;
		}
		return view;
	}
	
}
